<template>
  <el-drawer
    direction="rtl"
    custom-class="demo-drawer"
    :title="title"
    ref="drawer"
    size="40%"
    :visible.sync="dialogFormVisible"
    :wrapperClosable="false"
  >
    <div class="demo-drawer__content">
      <el-form ref="form" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="作者" prop="title">
          <el-input v-model="form.author" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" prop="bookimg">
          <vab-upload :limit="1" name="file" :size="2" url="/upload" :imgfileList="filelist" @succestList="succestlist" />
        </el-form-item>
        <el-form-item label="类别" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择分类">
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <template>
            <div v-if="dialogFormVisible" class="EditorBox" style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="form.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
              />
              <span class="wordNumber">{{ TiLength }}/{{ maxTextNum }}</span>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" controls-position="right"></el-input-number>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="close" type="warning">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
  import VabUpload from '@/components/VabUpload'
  import Vue from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { EditBooksChapter, AddBooksChapter, SysGetChapterFromBook } from '@/api/table'
  import { AddText, SetText } from '@/api/ad'
  import { SelTextType } from '@/api/userManagement'

  export default Vue.extend({
    components: { Editor, Toolbar, VabUpload },
    name: 'TableEdit',
    data() {
      const contentValidator = (rule, value, callback) => {
        this.TiLength = this.getSimpleText(value).length
        this.warnShow = this.TiLength > this.maxTextNum
        if (this.warnShow) {
          callback(new Error(`编辑内容不能超过${this.maxTextNum}个字!`))
        } else {
          callback()
        }
      }
      return {
        filelist: [],
        typeList: [],
        warnShow: false,
        TiLength: 0,
        maxTextNum: 20000,
        editor: null,
        toolbarConfig: {},
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            lineHeight: {
              lineHeightList: ['1', '1.25', '1.5', '1.75', '2'],
            },
            // 所有的菜单配置，都要在 MENU_CONF 属性下
            uploadImage: {
              // 后端上传地址，必填
              // server: 'http://ds.muqian.top/Upload/File',
              server: 'https://ds.muqian.top/Upload/EditorFile',
              timeout: 5 * 1000, // 5s 超时时间
              fieldName: 'File',
              //选择文件时的类型限制，默认为['image/*'] 如不想限制，则设置为 []
              allowedFileTypes: ['image/*'],
              // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
              meta: {
                filename: 'ZYTBtextSplitImg',
              },
              maxFileSize: 10 * 1024 * 1024, //2M //设置大点 不然图片过大会报错
              base64LimitSize: 5 * 1024, // 5kb 以下插入 base64
              // 上传前
              onBeforeUpload(file) {
                console.log('onBeforeUpload', file)
                return file
                return file.url // 返回哪些文件可以上传
                // return false 会阻止上传
              },
              // 上传进度的回调函数
              onProgress(progress) {
                console.log('onProgress', progress)
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log('onSuccess', file.url, res)
              },
              // 单个文件上传失败
              onFailed(file, res) {
                alert(res.message)
                console.log('onFailed', file, res)
              },
              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                alert(err.message)
                console.error('onError', file, err, res)
              },
            },
          },
        },
        mode: 'default', // or 'simple'
        form: {
          typeId: '',
          title: '',
          author: '',
          content: '',
          imgPath: '',
        },
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入章节名称' }],
          typeId: [{ required: true, trigger: 'blur', message: '请选择类别' }],
          content: [
            { required: true, trigger: 'blur', message: '请输入章节内容' },
            { required: true, trigger: 'change', validator: contentValidator },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    watch: {
      'form.content'(newvel) {
        this.TiLength = this.getSimpleText(newvel).length
        this.warnShow = this.TiLength > this.maxTextNum
      },
    },
    mounted() {},
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    async created() {},
    methods: {
      succestlist(e) {
        this.form.imgPath = e[0].response.data
      },
      getSimpleText(html) {
        var re1 = new RegExp('<.+?>', 'g') // 匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
        var msg = html.replace(re1, '') // 执行替换成空字符
        msg = msg.replace(/&nbsp;/g, ' ') // 去除 &nbsp;
        msg = msg.replace(/\s/g, '') // 去除空格;
        return msg
      },
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
      async showEdit(row) {
        this.filelist = []
        let { data } = await SelTextType({ typeName: '' })
        this.typeList = data
        if (!row) {
          this.title = '新增文章'
        } else {
          this.title = '编辑文章'
          this.form = Object.assign({}, row)
          this.filelist.push({ url: this.$baseImageUrl + this.form.imgPath })
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.$emit('fetch-data')
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { msg } = this.title === '新增文章' ? await AddText(this.form) : await SetText(this.form)
            this.$baseMessage(msg, 'success')
            this.$refs['form'].resetFields()
            this.dialogFormVisible = false
            this.$emit('fetch-data')
            this.form = this.$options.data().form
          } else {
            return false
          }
        })
      },
    },
  })
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
  ::v-deep .demo-drawer__content {
    height: 100%;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    .demo-drawer__footer {
      bottom: 0;
    }
    .EditorBox {
      position: relative;
      padding-bottom: 30px;
      .wordNumber {
        color: #909399;
        background: #fff;
        text-align: right;
        z-index: 100;
        right: 10px;
        bottom: 5px;
        font-size: 12px;
        position: absolute;
      }
    }
  }
</style>
